package com.yanyu.space.common.core.bean.web;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.yanyu.space.common.core.bean.enums.IRCode;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yanyu
 */
@Data
public class R<T> {

    protected int code;

    protected String msg;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    protected T bean;

    public static <T> R<T> ok() {
        return ok(null);
    }

    public static <T> R<T> ok(T bean) {
        R<T> result = new R<>();
        result.code = RCode.SUCCESS.getCode();
        result.msg = RCode.SUCCESS.getMsg();
        result.bean = bean;
        return result;
    }

    public static <T> R<T> fail() {
        return fail(RCode.FAIL.getCode(), RCode.FAIL.getMsg(), null);
    }

    public static <T> R<T> fail(IRCode rCode) {
        return fail(rCode.getCode(), rCode.getMsg(), null);
    }

    public static <T> R<T> fail(IRCode rCode, T bean) {
        return fail(rCode.getCode(), rCode.getMsg(), bean);
    }

    public static <T> R<T> fail(IRCode rCode, String msg, T bean) {
        return fail(rCode.getCode(), msg, bean);
    }

    private static <T> R<T> fail(int code, String msg, T bean) {
        R<T> result = new R<>();
        result.code = code;
        result.msg = msg;
        result.bean = bean;
        return result;
    }

    public static Builder newMap() {
        return new Builder();
    }

    @Data
    public static class Builder {

        private R<Map> r = ok(new HashMap());

        public Builder put(String key, Object value) {
            r.bean.put(key, value);
            return this;
        }

        public R<Map> build() {
            return r;
        }
    }
}
